package com.wanbatv.wangwangba;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.wanbatv.wangwangba.chengzhang.WeinxinTouxiang;
import com.wanbatv.wangwangba.chengzhang.WeixinZhaopian_demo;
import com.wanbatv.wangwangba.util.BitmapCache;
import com.wanbatv.wangwangba.util.Util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import de.hdodenhof.circleimageview.CircleImageView;


public class ChengzhangrijiActivity extends Activity {
    private LinearLayout weixin_user_list_container;
    private LinearLayout chengzhangriji_layout;
    public static Map<String,Bitmap> map1=new HashMap<String,Bitmap>();
    private JSONArray arr_photo=null;
    private JSONArray arr_touxiang=null;

    private TreeMap<String,JSONArray> map=new TreeMap<String,JSONArray>();
    ImageLoader mImageLoader = null;
    RequestQueue mRequestQueue = null;
    ArrayList<String> urls1 = new ArrayList<>();
    ArrayList<String> urls2 = new ArrayList<>();
    ArrayList<String> urls3 = new ArrayList<>();
    MyItemClickListener mListener;
    int position1=0;
    public static String weixin_video_url=null;
    public static boolean weixin_video_bool=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chengzhangriji);
        position1=0;
        weixin_user_list_container=(LinearLayout)findViewById(R.id.weixin_user_list_container);
        RequestQueue rq = Volley.newRequestQueue(ChengzhangrijiActivity.this.getApplicationContext());
//        JsonObjectRequest request = new JsonObjectRequest("http://121.201.14.248/wanba/photo_ajax_0907.jsp?userId=" + Util.getDeviceId(ChengzhangrijiActivity.this), null,
        JsonObjectRequest request = new JsonObjectRequest("http://121.201.14.248/wangwangba/data.jsp?userId="+ Util.getDeviceId(ChengzhangrijiActivity.this), null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            JSONArray arr=jsonObject.getJSONArray("userList");
                            arr_touxiang=arr;
                            arr_photo=jsonObject.getJSONArray("mediaList");

                            for ( int i=0;i<arr.length();i++) {
                                WeinxinTouxiang v1 = new WeinxinTouxiang(ChengzhangrijiActivity.this);
                                final CircleImageView iv=(CircleImageView)v1.findViewById(R.id.login_weixing_touxiang);
                                TextView tv=(TextView)v1.findViewById(R.id.login_weixin_name);
                                JSONObject obj=arr.getJSONObject(i);
                                tv.setText(obj.getString("nickName"));
                                RequestQueue mQueue = Volley.newRequestQueue(ChengzhangrijiActivity.this);

                                ImageRequest imageRequest = new ImageRequest(
                                        obj.getString("avatar"),
                                        new Response.Listener<Bitmap>() {
                                            @Override
                                            public void onResponse(Bitmap response) {
                                                iv.setImageBitmap(response);
                                                map1.put( 8+ "touxiang", response);
                                            }
                                        }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
//                                    erweima_login.setImageResource(R.drawable.default_image);
                                    }
                                });
                                mQueue.add(imageRequest);
                                LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                lp.leftMargin=20;
                                weixin_user_list_container.addView(v1,lp);
                            }
                            for (int j=0;j<arr_photo.length();j++){
                                try {
                                    JSONArray arr_1=null;
                                    JSONObject obj_1=arr_photo.getJSONObject(j);
                                    if(map.get(obj_1.getString("uploadDate"))==null){
                                        arr_1=new JSONArray();
                                        map.put(obj_1.getString("uploadDate"),arr_1);
                                    }
                                    arr_1 = map.get(obj_1.getString("uploadDate"));
                                    arr_1.put(obj_1);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            init();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }

        );
        rq.add(request);

        chengzhangriji_layout=(LinearLayout)findViewById(R.id.chengzhangriji_layout);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_chengzhangriji, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    private void init(){
        for (String key:map.descendingKeySet()){
            TextView tv=new TextView(ChengzhangrijiActivity.this);
            tv.setText(key);
            tv.setTextColor(0xFFFFFFFF);
            tv.setTextSize(20);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.topMargin=20;
            chengzhangriji_layout.addView(tv, lp);
            LinearLayout layout1=new LinearLayout(ChengzhangrijiActivity.this);
            layout1.setOrientation(LinearLayout.VERTICAL);
//            layout1.setBackgroundColor(0x80000000);
            layout1.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
            ));
            chengzhangriji_layout.addView(layout1);
            JSONArray arr_bianli=map.get(key);
            int changdu=arr_bianli.length()/5;
            int num=0;
            if(arr_bianli.length()%5!=0){
                changdu+=1;
            }
            for (int a=0;a<changdu;a++) {
                LinearLayout layout2=new LinearLayout(ChengzhangrijiActivity.this);
                layout2.setOrientation(LinearLayout.HORIZONTAL);
//            layout1.setBackgroundColor(0x80000000);
                layout2.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
                ));
                LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                lp2.topMargin=20;

                layout1.addView(layout2, lp2);
                mRequestQueue = Volley.newRequestQueue(this.getApplicationContext());
                mImageLoader = new ImageLoader(mRequestQueue, new BitmapCache());
                if(num+5<arr_bianli.length()){
                    for (int j = 0; j < 5; j++) {
                        WeixinZhaopian_demo demo = new WeixinZhaopian_demo(ChengzhangrijiActivity.this);
                        LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        lp1.leftMargin = 20;
                        lp1.weight = 0;
                        try {
                            JSONObject obj=arr_bianli.getJSONObject(j);
                            setphoto(num, demo, arr_bianli, position1);
                            layout2.addView(demo, lp1);
                            num+=1;
                            position1 += 1;
                        }catch (JSONException e){
                            e.printStackTrace();
                        }

                    }
                }else{
                    int num1=arr_bianli.length()-num;

                    for (int j = 0; j < num1; j++) {
                        WeixinZhaopian_demo demo = new WeixinZhaopian_demo(ChengzhangrijiActivity.this);
                        LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        lp1.leftMargin = 20;
                        lp1.weight = 0;
                        try {
                            JSONObject obj=arr_bianli.getJSONObject(j);
                            setphoto(num, demo, arr_bianli, position1);
                            layout2.addView(demo, lp1);
                            num+=1;
                            position1 += 1;
                        }catch (JSONException e){
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Iterator iter = map1.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey();
            Object val = entry.getValue();
            Bitmap a=(Bitmap)val;
            a.recycle();
        }
        System.gc();
    }
    public void setphoto(int num,WeixinZhaopian_demo v,JSONArray arr_num,int position1){
        JSONObject object= null;
        try {
            object = arr_num.getJSONObject(num);
            TextView tv=(TextView)v.findViewById(R.id.weixin_demo_shijian);
            ImageView iv1=(ImageView)v.findViewById(R.id.weixin_demo_iv1);
            ImageView iv_video=(ImageView)v.findViewById(R.id.weixin_demo_video);
            CircleImageView iv2=(CircleImageView)v.findViewById(R.id.weixin_demo_touxiang);
            tv.setText(object.getString("uploadDate"));
            String url=object.getString("iconSrc");
            String userId=object.getString("weixinId");
//            if(object.getString("mediaType").equals("img")) {
            urls1.add(object.getString("src"));
//            }else{
//                urls1.add(object.getString("iconSrc"));
//            }
            urls2.add(object.getString("mediaType"));
            urls3.add(object.getString("iconSrc"));
            if(object.getString("mediaType").equals("img")){
                iv_video.setVisibility(View.GONE);
            }else{
                iv_video.setVisibility(View.VISIBLE);
            }
            String url_video=object.getString("src");
            mListener = new MyItemClickListener(position1,iv_video,url_video);
            iv1.setOnClickListener(mListener);

            if(Login2Activity.chengzhang_num_pindao==1){
                if(position1==0){
                    iv1.requestFocus();
                }
            }else if(Login2Activity.chengzhang_num_pindao==2 && Login2Activity.chengzhang_num1!=0){
                if(position1==Login2Activity.chengzhang_num1){
                    iv1.requestFocus();
                }
            }else if(Login2Activity.chengzhang_num_pindao==3 && Login2Activity.chengzhang_num1!=Login2Activity.chengzhang_num2){
                if(position1==Login2Activity.chengzhang_num2){
                    iv1.requestFocus();
                }
            }else if(Login2Activity.chengzhang_num_pindao==4 && Login2Activity.chengzhang_num2!=Login2Activity.chengzhang_num3){
                if(position1==Login2Activity.chengzhang_num3){
                    iv1.requestFocus();
                }
            }else{
                if(position1==0){
                    iv1.requestFocus();
                }
            }
            String TX_URL=null;
            for(int a=0;a<arr_touxiang.length();a++) {
                JSONObject tx = arr_touxiang.getJSONObject(a);
                if (tx.getString("weixinId").equals(userId)) {
                    TX_URL = tx.getString("avatar");
                }
            }
            if (TX_URL != null) {
                mImageLoader.get(TX_URL, ImageLoader.getImageListener(
                                iv2, 0, 0),
                        iv2.getWidth(),
                        iv2.getHeight(),
                        ImageView.ScaleType.CENTER_CROP);
            }
            mImageLoader.get(url, ImageLoader.getImageListener(
                            iv1, 0, 0),
                    iv1.getWidth(),
                    iv1.getHeight(),
                    ImageView.ScaleType.CENTER_CROP);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    public class MyItemClickListener implements View.OnClickListener {

        int position;
        ArrayList<String> urls = urls1;
        ArrayList<String> url2 = urls2;
        ArrayList<String> url3 = urls3;
        ImageView view;
        String url;
        public MyItemClickListener(int position,ImageView view,String url){
            this.position=position;
            this.view=view;
            this.url=url;

        }

        /**
         * Called when a view has been clicked.
         *
         * @param v The view that was clicked.
         */
        @Override
        public void onClick(View v) {
//            if(view.getVisibility()==View.VISIBLE){
//                weixin_video_bool=true;
//                weixin_video_url=url;
//                Intent intent = new Intent();
//                intent.setClass(ChengzhangrijiActivity.this, ShowBofangActivity.class);
//                startActivity(intent);
//            }else {
            Intent intent = new Intent();
            intent.setClass(ChengzhangrijiActivity.this, ChengzhangrijiNeirongActivity.class);
            intent.putExtra("position", this.position);
            intent.putExtra("urls", this.urls);
            intent.putExtra("urls2", this.url2);
            intent.putExtra("urls3", this.url3);
            startActivity(intent);
//            }

        }
    }
}
